#region License
/*

	Copyright (C) 2008 Oliver Charles, Daniel Hollander

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/
#endregion

using System;
using Tao.DevIl;
using Tao.OpenGl;
using Moebius.Core;

namespace Moebius.Rendering.OpenGL
{
	 public class Texture : Rendering.ITexture
	 {
	      private int textureName;
		  private int[] glTextureName = {0};
		  private int mWidth;
		  private int mHeight;
		
		  public int Width
		  {
			   get { return mWidth; }
		  }
		
		  public int Height
		  {
			   get { return mHeight; }
		  }
		
		  public Texture()
		  {
			   Il.ilGenImages(1, out textureName);
		  }
		
		  internal void Load(string filename, ILogger logger)
		  {
			   Il.ilBindImage(textureName);
			   if(Il.ilLoadImage(filename))
			   {
					if(Il.ilConvertImage(Il.IL_RGBA, Il.IL_UNSIGNED_BYTE))
					{
						 Gl.glGenTextures(1, glTextureName);
						 Gl.glBindTexture(Gl.GL_TEXTURE_2D, glTextureName[0]);
					
						 Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
						 Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
					
						 mWidth = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
						 mHeight = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);

						 if(logger != null)
							  logger.LogInfo(string.Format("Texture dimensions are {0}x{1}", mWidth, mHeight));
					
						 Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Il.ilGetInteger(Il.IL_IMAGE_BPP),
										 mWidth, mHeight, 0,
										 Il.ilGetInteger(Il.IL_IMAGE_FORMAT), Gl.GL_UNSIGNED_BYTE, Il.ilGetData());
					
						 Il.ilDeleteImages(1, ref textureName);
					} else
						 if(logger != null)
							  logger.LogInfo("Could not convert image");
			   } else
					if(logger != null)
						 logger.LogInfo("Could not load");
		  }
				
		
		  public void Activate()
		  {
			   Gl.glEnable(Gl.GL_TEXTURE_2D);
			   Gl.glBindTexture(Gl.GL_TEXTURE_2D, glTextureName[0]);
		  }
	 }
}